<?php

namespace App\Http\Controllers\Api;

use App\Http\Requests\Api\PostsRequest;
use App\Models\Posts;
use App\Transformers\PostsTransformer;
use Illuminate\Http\Request;

class PostsController extends Controller
{
    public function index(Request $request)
    {
        $key = $request->only([
            //??
        ]);

        $data = Posts::where('is_show', 1)->where($key)->orderBy('created_at', 'desc')->paginate();

        return $this->response->paginator($data, new PostsTransformer([], $this->user));
    }

    public function show($id)
    {
        $data = Posts::find($id);

        if (!$data) {
            $this->response->error(trans('api.not_exists'), 200);
        }

        //增加浏览量
        $data->increment('view_amount');

        return $this->response->item($data, new PostsTransformer([], $this->user));
    }

    public function create(PostsRequest $request)
    {
        $data = $request->only([
            'title', 'content', 'pictures',
        ]);

        if (!$data) {
            $this->response->error(trans('api.save_failed'), 200);
        }

        $data['object_id'] = $this->user->id;
        $data['object_type'] = 'App\Models\User';

        $res = Posts::create($data);

        if ($res) {
            return response()->json(['message' => trans('api.save_succeed'), 'code' => 1, 'status' => true, 'data' => ''], 200);
        } else {
            return response()->json(['message' => trans('api.save_failed'), 'code' => 0, 'status' => false], 200);
        }
    }
}
